//
//  SNOrderFormListViewController.m
//  app
//
//  Created by 王少宁 on 15/5/5.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//  订单列表

#import "SNOrderFormListViewController.h"
#import "SNOrderFormListDataManager.h"
#import "SNOrderFormListHeaderView.h"
#import "SNOrderFormListCell.h"
#import "SNOrderFormListModel.h"
#import "SNOrderFormDetailViewController.h"

#define LIMIT 15

@interface SNOrderFormListViewController ()<UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource,SNOrderFormListHeaderViewDeletage>
@property (nonatomic, retain) UITableView * myTableView;
@property (nonatomic, retain) SNOrderFormListDataManager * manager;
@property (nonatomic, retain) SNOrderFormListHttpResult * result;
@property (nonatomic, retain) SNDeleteOrderHttpResult * deleteResult;
@property (nonatomic, assign) int viewApperCount;
@property (nonatomic, assign) int lastID;
@property (nonatomic, copy) NSString * listOstatus;//什么类型的订单 0未支付，1支付成功，2已发货，4完成(签收)，5已失效(过期未支付)，6订单取消,8 备货中, -1所有状态的订单
@property (nonatomic, assign) int deleteSection;
@end

@implementation SNOrderFormListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.viewApperCount = 0;
    self.lastID = 0;
    
    switch (self.style) {
        case 0:
            self.navigationItem.title = @"待支付";
            self.listOstatus = @"0";
            break;
        case 1:
            self.navigationItem.title = @"待收货";
            self.listOstatus = @"1|2|8";
            break;
        case 2:
            self.navigationItem.title = @"全部订单";
            self.listOstatus = @"-1";
            break;
        case 3:
            self.navigationItem.title = @"待评价";
            self.listOstatus = @"4";
            break;
        case 4:
            self.navigationItem.title = @"退换货";
            self.listOstatus = @"-2";
            break;
        default:
            break;
    }
    
    self.result = [[SNOrderFormListHttpResult alloc] initWithTarget:self action:@selector(loadingData:)];
    self.deleteResult = [[SNDeleteOrderHttpResult alloc] initWithTarget:self action:@selector(deleteResult:)];
    self.manager = [SNOrderFormListDataManager shareManager];
    [self createTableView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [self requestWithLastid:self.lastID limit:LIMIT ostatus:self.listOstatus];
    self.viewApperCount++;
}


- (void)createTableView
{
    self.myTableView = CREATE_WITH_FRAME_OF(UITableView, CGPointMake(0, 0),
                                            [self.view.ubo ow:SCREEN_WIDTH oh:ScreenHeight],
                                            style:UITableViewStyleGrouped);
    self.myTableView.contentInset = UIEdgeInsetsMake(self.navigationAndStatusBarHeight, 0, 0, 0);
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.separatorColor = [UIColor clearColor];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    self.myTableView.sectionHeaderHeight = 0;
    self.myTableView.sectionFooterHeight = 0;
    self.myTableView.headerRefreshController = [[UIRefreshHeaderController alloc] initWithTableView:self.myTableView caller:[UBTargetCaller of:self action:@selector(refreshData)]];
    self.myTableView.footerRefreshController = [[UIRefreshFooterController alloc] initWithTableView:self.myTableView caller:[UBTargetCaller of:self action:@selector(loadMoreData)]];
    self.myTableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc] initWithView:self.myTableView viewController:self tryAgain:@selector(refreshData)];
    [self.view addSubview:self.myTableView];
}

- (void)refreshData
{
    [self requestWithLastid:0 limit:LIMIT ostatus:self.listOstatus];
}

- (void)loadMoreData
{
    SNOrderFormListHeaderModel * model = [self.result.dataArray lastObject];
    self.lastID = model.orderFormId;
    
    [self requestWithLastid:self.lastID limit:LIMIT ostatus:self.listOstatus];
}

- (void)requestWithLastid:(int)lastid limit:(int)limit ostatus:(NSString *)ostatus
{
    if (self.viewApperCount == 0) {
        [self.myTableView.nothingRefreshView show];
    }
    [self.manager loadOrderFormListData:self.result lastid:lastid limit:limit ostatus:ostatus];
}

- (void)loadingData:(SNOrderFormListHttpResult *)result
{
    if (result.success) {
        [self.myTableView endRefreshingAll];
        [self.myTableView.nothingRefreshView remove];
        [self.myTableView reloadData];
    } else if (result.failure) {
        [self.myTableView.nothingRefreshView activeStop];
    }
    
    for (SNOrderFormListHeaderModel * model in result.dataArray) {
        DLog(@"%d",model.orderFormId);
    }
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (self.result.noData) {
        return 1;
    } else {
        return self.result.dataArray.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.result.noData) {
        return 0;
    } else {
        SNOrderFormListHeaderModel * model = self.result.dataArray[section];
        
        if (self.result.noMoreData) {//没有更多数据
            if (section == self.result.dataArray.count-1) {
                return model.product_info.count+1;
            } else {
                return model.product_info.count;
            }
        } else {
            return model.product_info.count;
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SNOrderFormListHeaderModel * model = self.result.dataArray[indexPath.section];
    
    static NSString * identifier = @"cell";
    SNOrderFormListCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[SNOrderFormListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    if (self.result.noMoreData) {//没有更多数据
        if (indexPath.section == self.result.dataArray.count-1) {
            if (indexPath.row == model.product_info.count) {
                NoMoreDataCell * cell = [[NoMoreDataCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"identifier"];
                cell.backgroundColor = [UIColor clearColor];
                return cell;
            } else {
                SNOrderFormListModel * cellModel = model.product_info[indexPath.row];
                [cell cellWithModel:cellModel];
                return cell;
            }
        } else {
            SNOrderFormListModel * cellModel = model.product_info[indexPath.row];
            [cell cellWithModel:cellModel];
            return cell;
        }
    } else {
        SNOrderFormListModel * cellModel = model.product_info[indexPath.row];
        [cell cellWithModel:cellModel];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self pushToOrderFormDetailVCWithSection:indexPath.section];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (self.result.noData) {
        UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        UILabel * label = [[UILabel alloc] initWithFrame:view.frame];
        label.text = @"暂无订单";
        label.textColor = [XCommon hexStringToColor:kColor_m_light_gray_text];
        label.font = JKAppGlobleFontContentText;
        label.textAlignment = NSTextAlignmentCenter;
        [view addSubview:label];
        return view;
    } else {
        SNOrderFormListHeaderView * view = [[SNOrderFormListHeaderView alloc] init];
        view.section = section;
        view.deletage = self;
        SNOrderFormListHeaderModel * model = self.result.dataArray[section];
        [view viewWithModel:model];
        return view;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (self.result.noData) {
        return 40;
    } else {
        return kOrderFormListHeaderViewHeight;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SNOrderFormListHeaderModel * model = self.result.dataArray[indexPath.section];
    
    if (self.result.noMoreData) {
        if (indexPath.section == self.result.dataArray.count-1) {
            if (indexPath.row == model.product_info.count) {
                return kNoMoreDataCellHeight-20;
            } else {
                return kOrderFormListCellHeight;
            }
        } else {
            return kOrderFormListCellHeight;
        }
    } else {
        return kOrderFormListCellHeight;
    }
}

-(void)orderFormListHeaderViewMainBtnClick:(NSString *)sectionStr
{
    NSInteger section = [sectionStr integerValue];
    [self pushToOrderFormDetailVCWithSection:section];
}

- (void)pushToOrderFormDetailVCWithSection:(NSInteger)section
{
    SNOrderFormDetailViewController * detailVC = [[SNOrderFormDetailViewController alloc] init];
    SNOrderFormListHeaderModel * model = self.result.dataArray[section];
    detailVC.sn = model.sn;
    detailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - 删除订单
- (void)deleteOrderBtnClick:(NSString *)sectionStr
{
    UIAlertView * av = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定删除订单" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    
    self.deleteSection = [sectionStr integerValue];
    
    [av show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (!buttonIndex) {
        SNOrderFormListHeaderModel * model = self.result.dataArray[self.deleteSection];
        [MBProgressHUD showMBProgressHUBOnWindowsWithMessage:@"删除订单中..."];
        [self.manager deleteOrederFormList:self.deleteResult sn:model.sn];

    }
}

- (void)deleteResult:(SNDeleteOrderHttpResult *)result
{
    sleep(1);
    [MBProgressHUD dismissMBProgressHUBOnWindows];
    if (result.success) {
        [MyToast showDefaultBottonWithText:@"删除订单成功"];
        [self refreshData];
    } else {
        [MyToast showDefaultBottonWithText:@"删除订单失败,请重试..."];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
